package com.yikome.monitor.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yikome.monitor.request.CreateMonitorRequest;
import com.yikome.monitor.service.MonitorUtService;
import com.yikome.shop.utils.RequestUtils;
import com.yikome.utils.JSONUtils;
import com.yikome.utils.NetworkUtils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/monitor")
public class MonitorApi {

	@Autowired
	private MonitorUtService monitorService ; 
	
	public static final String[] outIps = {"117.22.27.102" , "1.80.195.235" , "112.118.57.62" , "42.200.121.247" , "52.175.13.19"};
	
	@PostMapping
	public boolean saveMonitorForPost(@RequestBody List<CreateMonitorRequest> monitorRequests , HttpServletRequest request) {
		try {
			String ip = NetworkUtils.getIpAddress(request);
			
			if(!CollectionUtil.contains(Arrays.asList(outIps), ip)) {
				for (CreateMonitorRequest monitor : monitorRequests) {
					CreateMonitorRequest filterERPMonitorParamsPO = filterERPMonitorParamsPO(monitor);
					if(filterERPMonitorParamsPO != null) {
						monitorService.consumeMessage(JSONUtils.toJsonString(monitor));
					}
				}
			}
		}catch (Exception e) {
			log.error(e.getMessage());
		}
		
		return true;
	} 

	@GetMapping(value="/ut")
	public void saveMonitorForUt(HttpServletRequest request , HttpServletResponse response) {
		try {
			String ip = NetworkUtils.getIpAddress(request);
			
			if(!StrUtil.containsAny(ip, outIps)) {
				Map<String, Object> paramsMap = RequestUtils.converToMapFirst(request);
				CreateMonitorRequest monitor = JSONUtils.map2Bean(paramsMap, CreateMonitorRequest.class);
				CreateMonitorRequest filterERPMonitorParamsPO = filterERPMonitorParamsPO(monitor);
				if(filterERPMonitorParamsPO != null) {
					monitorService.consumeMessage(JSONUtils.toJsonString(monitor));
				}
			}
			
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}
	
	private CreateMonitorRequest filterERPMonitorParamsPO(CreateMonitorRequest monitor) {
		
		if(StrUtil.equalsAny(monitor.getAimsCategory(), "PRODUCT") && StrUtil.isBlank(monitor.getEventAims())) return null ; 
		
		return monitor;
	}
}
